package com.fadadianqi.logistics.admin.net;

import com.fadadianqi.logistics.admin.net.mina.ClientSession;
import com.yeqiangwei.commons.util.Utils;
import com.yeqiangwei.commons.util.ValidatorHelper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class SessionManager {

    public static void main(String args[]) throws InterruptedException {
        SessionManager.addSession(new ClientSession(null));
        SessionManager.addSession(new ClientSession(null));
        for (int i = 0; i < 10; i++) {
            Session sess = SessionManager.getCurrentSession();
            System.out.println(sess);
            Thread.sleep(1000);
        }

    }

    private static final ConcurrentHashMap<String, Session> SESSION_CACHE = new ConcurrentHashMap<String, Session>();

    public static List<Session> getSessionList() {
        Iterator<String> it = SESSION_CACHE.keySet().iterator();
        List<Session> list = new ArrayList<Session>();
        while (it.hasNext()) {
            list.add(SESSION_CACHE.get(it.next()));
        }
        return list;
    }

    public static Session getCurrentSession() {
        List<Session> list = getSessionList();
        if (ValidatorHelper.isEmpty(list)) {
            return null;
        }
        int i = list.size();
        if (i == 1) {
            return list.get(0);
        }
        int n = Utils.getRandomNumber(0, i - 1).intValue();
        return list.get(n);
    }

    public static final void addSession(Session session) {
        if (session != null)
            SESSION_CACHE.put(session.getId(), session);
    }

    public static final void delSession(Session session) {
        if (session != null)
            delSession(session.getId());
    }

    public static final void delSession(long id) {
        delSession(String.valueOf(id));
    }

    public static final void delSession(String id) {
        SESSION_CACHE.remove(id);
    }

    public static final Session getSession(String id) {
        return SESSION_CACHE.get(id);
    }

    public static final Session getSession(long id) {
        return SESSION_CACHE.get(String.valueOf(id));
    }
}
